const fs = require('fs');
const path = require('path');
 
function moveDirectory(source, destination, callback) {
     deleteDirectoryRecursive(destination); // 判断是否有文件夹，如果有则先删除
    fs.rename(source, destination, function (err) {
    if (err) {
      if (err.code === 'EXDEV') {
        // 如果错误码是EXDEV，意味着需要执行一个跨设备的文件重命名操作。
        moveDirectoryAcrossDevices(source, destination, callback);
      } else {
        callback(err);
      }
    } else {
      callback();
    }
  });
}
 
function moveDirectoryAcrossDevices(source, destination, callback) {
  // 先复制再删除
  fs.copyDirectory(source, destination, (err) => {
    if (err) {
      callback(err);
    } else {
      fs.removeDirectory(source, callback);
    }
  });
}
 
// 删除out
function deleteDirectoryRecursive(directoryPath) {
    if (fs.existsSync(directoryPath)) {
        fs.readdirSync(directoryPath).forEach(function(file, index) {
          var curPath = path.join(directoryPath, file);
          if (fs.lstatSync(curPath).isDirectory()) {
            // Recurse
            deleteDirectoryRecursive(curPath);
          } else {
            // Delete file
            fs.unlinkSync(curPath);
          }
        });
        fs.rmdirSync(directoryPath);
      }
}

// 使用示例
const srcDir = path.join(__dirname, './electron/out');
const destDir = path.join(__dirname, './out');
 
moveDirectory(srcDir, destDir, (err) => {
  if (err) {
    console.error('移动文件夹失败:', err);
  } else {
    console.log('文件夹移动成功。');
  }
});
